package com.zzy.transaction.context;

import cn.hutool.core.lang.UUID;
import com.zzy.transaction.future.Monitor;
import com.zzy.transaction.manager.TransactionCoordinator;
import lombok.Data;
import org.springframework.beans.factory.InitializingBean;

import java.util.concurrent.*;

@Data
public class TransactionMeta implements InitializingBean {

    private int taskCount;
    private long timeout;
    private TimeUnit timeUnit;
    private CountDownLatch countDownLatch;
    private String executeId;
    private CompletableFuture<Boolean> completableFuture;
    private Monitor monitor;

    public void setTaskCount(int taskCount) {
        this.taskCount = taskCount;
    }

    @Override
    public void afterPropertiesSet() {
        this.countDownLatch = new CountDownLatch(taskCount);
        this.executeId = UUID.fastUUID().toString(true);
        this.completableFuture = new CompletableFuture<>();
    }

    public void finish(boolean success) {
        this.completableFuture.complete(success);
    }

    public boolean get(long timeout, TimeUnit unit) throws Exception {
        try {
            return this.completableFuture.get(timeout, unit);
        } catch (Throwable cause) {
            return this.getMonitor().timeoutRelease(this, cause);
        }
    }

}
